package org.jeecg.modules.htxincailiao.analytics.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.contant.HTClient;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.IPInfo;
import org.jeecg.common.util.IPUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.htxincailiao.analytics.domain.dto.HTBackendVisitUpdateDTO;
import org.jeecg.modules.htxincailiao.analytics.domain.vo.HTBackendVisitDistributionVO;
import org.jeecg.modules.htxincailiao.analytics.entity.HTBackendVisitAction;
import org.jeecg.modules.htxincailiao.analytics.service.IHTBackendVisitActionService;
import org.jeecg.modules.htxincailiao.area.entity.HTArea;
import org.jeecg.modules.htxincailiao.area.service.IHTAreaService;
import org.jeecg.modules.permissions.HTRolePermission;
import org.jeecg.modules.permissions.HTRolePermissionDTO;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: ht_backend_visit_action
 * @Author: jeecg-boot
 * @Date: 2022-05-27 10:17:45
 * @Version: V1.0
 */
@Api(tags = "ht_backend_visit_action")
@RestController
@RequestMapping("/analytics/hTBackendVisitAction")
@Slf4j
public class HTBackendVisitActionController extends JeecgController<HTBackendVisitAction, IHTBackendVisitActionService> {
    @Resource
    private IHTBackendVisitActionService hTBackendVisitActionService;


    @Resource
    private ISysUserService sysUserService;

    @Resource
    private IHTAreaService areaService;


    /**
     * PV、UV 分布查询
     *
     * @param req       请求体
     * @param beginTime 开始时间
     * @param endTime   结束时间
     * @return pv、uv分布
     */
    @AutoLog(value = "ht_Backend_visit_action-分页列表查询")
    @ApiOperation(value = "ht_Backend_visit_action-分页列表查询", notes = "ht_Backend_visit_action-分页列表查询")
    @GetMapping(value = "/getDistribution")
    public Result<?> getDistribution(HttpServletRequest req, String beginTime, String endTime) {
        List<HTBackendVisitDistributionVO> list = hTBackendVisitActionService.getDistribution(beginTime, endTime);
        return Result.OK(list);
    }

    /**
     * 分页列表查询
     *
     * @param hTBackendVisitAction
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ht_backend_visit_action-分页列表查询")
    @ApiOperation(value = "ht_backend_visit_action-分页列表查询", notes = "ht_backend_visit_action-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HTBackendVisitAction hTBackendVisitAction,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<HTBackendVisitAction> queryWrapper = QueryGenerator.initQueryWrapper(hTBackendVisitAction, req.getParameterMap());
        Page<HTBackendVisitAction> page = new Page<HTBackendVisitAction>(pageNo, pageSize);
        IPage<HTBackendVisitAction> pageList = hTBackendVisitActionService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param hTBackendVisitAction
     * @return
     */
    @AutoLog(value = "ht_backend_visit_action-添加")
    @ApiOperation(value = "ht_backend_visit_action-添加", notes = "ht_backend_visit_action-添加")
//    @PutMapping(value = "/edit")
    @RequestMapping(value = "/add", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> add(HttpServletRequest request, @RequestBody HTBackendVisitAction hTBackendVisitAction) {
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        if (oConvertUtils.isEmpty(token)) {
            return Result.error("请先登录");
        }
        String ip = IPUtil.getClientIp(request);
//        String ip = "182.149.201.158";
        IPInfo info = null;
        try {
//           info = IPUtil.getIPInfo("182.149.201.158");
            info = IPUtil.getIPInfo(ip);
        } catch (URISyntaxException | IOException ignored) {
        }

        if (oConvertUtils.isNotEmpty(ip)) {
            hTBackendVisitAction.setVisitIp(ip);
        }

        Result<JSONObject> result = new Result<>();

        String username = null;
        if (oConvertUtils.isNotEmpty(token)) {
            username = JwtUtil.getUsername(token);
        }
        HTRolePermissionDTO roleDTO = HTRolePermission.GetLoginUserPermissionInfo(request);
        String shopId = HTRolePermission.GetLoginUserShopId(request);
        SysUser sysUser = null;
        if (oConvertUtils.isNotEmpty(username)) {
            sysUser = sysUserService.getUserByName(username);
        }
        if (oConvertUtils.isEmpty(sysUser)) {
            sysUser = sysUserService.getUserByPhoneNumber(username);
        }

        if (oConvertUtils.isNotEmpty(roleDTO.getRoleId()))
            hTBackendVisitAction.setRoleId(roleDTO.getRoleId());

        if (oConvertUtils.isNotEmpty(shopId))
            hTBackendVisitAction.setShopId(shopId);

        if (oConvertUtils.isNotEmpty(sysUser))
            hTBackendVisitAction.setSysUserId(sysUser.getId());


        if (oConvertUtils.isNotEmpty(hTBackendVisitAction.getClientOsString())) {
            Integer clientOs = HTClient.GetClientOsIndex(hTBackendVisitAction.getClientOsString());
            hTBackendVisitAction.setClientOs(clientOs);
        }

        String provinceName = oConvertUtils.isNotEmpty(info) ? info.getProvinceName() : null;
        if (oConvertUtils.isNotEmpty(provinceName)) {
            List<HTArea> list = areaService.queryByName(provinceName);
            if (!list.isEmpty()) {
                HTArea area = list.stream().findFirst().orElse(null);
                if (oConvertUtils.isNotEmpty(area)) {
                    hTBackendVisitAction.setProvinceId(area.getId());
                }

            }
        }
        String provinceId = hTBackendVisitAction.getProvinceId();
        if (oConvertUtils.isNotEmpty(provinceId)) {
            List<HTArea> list = areaService.fuzzyQueryByName(provinceName);
            if (!list.isEmpty()) {
                HTArea area = list.stream().findFirst().orElse(null);
                if (oConvertUtils.isNotEmpty(area)) {
                    hTBackendVisitAction.setProvinceId(area.getId());
                }
            }
        }

        if (oConvertUtils.isNotEmpty(hTBackendVisitAction.getSysUserId()) && hTBackendVisitActionService.save(hTBackendVisitAction)) {
            JSONObject obj = new JSONObject();
            obj.put("visitInfo", hTBackendVisitAction);
            result.setResult(obj);

        } else {
            result.error500("保存访问日志失败");

        }
        return result;
    }

    /**
     * 编辑
     *
     * @param body 请求参数
     * @return
     */
    @AutoLog(value = "ht_backend_visit_action-编辑")
    @ApiOperation(value = "ht_backend_visit_action-编辑", notes = "ht_backend_visit_action-编辑")
    @RequestMapping(value = "/visitEdit", method = {RequestMethod.POST})
    public Result<?> visitEdit(HttpServletRequest request, @RequestBody String body) throws IOException {
        HTBackendVisitUpdateDTO dto = JSONObject.parseObject(body, HTBackendVisitUpdateDTO.class);
        if (oConvertUtils.isNotEmpty(dto.getId())) {
            HTBackendVisitAction htBackendVisitAction = hTBackendVisitActionService.getById(dto.getId());
//System.out.printf("\n\n\nvisit edit %s \n\n\n", JSONObject.toJSONString(htBackendVisitAction));
            //  只更新需要更新的数据即可
            if (oConvertUtils.isNotEmpty(dto.getLeaveTime())) {
                htBackendVisitAction.setLeaveTime(dto.getLeaveTime());
                hTBackendVisitActionService.updateById(htBackendVisitAction);
            }
        }

        return Result.OK("编辑成功!");
    }

    /**
     * 编辑
     *
     * @param hTBackendVisitAction
     * @return
     */
    @AutoLog(value = "ht_backend_visit_action-编辑")
    @ApiOperation(value = "ht_backend_visit_action-编辑", notes = "ht_backend_visit_action-编辑")
    //    @PutMapping(value = "/edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> edit(@RequestBody HTBackendVisitAction hTBackendVisitAction) {
//        System.out.printf("\n\n\n hTBackendVisitAction%s \n\n\n", JSONObject.toJSONString(hTBackendVisitAction));
        hTBackendVisitActionService.updateById(hTBackendVisitAction);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_backend_visit_action-通过id删除")
    @ApiOperation(value = "ht_backend_visit_action-通过id删除", notes = "ht_backend_visit_action-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        hTBackendVisitActionService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "ht_backend_visit_action-批量删除")
    @ApiOperation(value = "ht_backend_visit_action-批量删除", notes = "ht_backend_visit_action-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hTBackendVisitActionService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_backend_visit_action-通过id查询")
    @ApiOperation(value = "ht_backend_visit_action-通过id查询", notes = "ht_backend_visit_action-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        HTBackendVisitAction hTBackendVisitAction = hTBackendVisitActionService.getById(id);
        if (hTBackendVisitAction == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(hTBackendVisitAction);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hTBackendVisitAction
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HTBackendVisitAction hTBackendVisitAction) {
        return super.exportXls(request, hTBackendVisitAction, HTBackendVisitAction.class, "ht_backend_visit_action");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HTBackendVisitAction.class);
    }

}
